package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.poji.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.*;
import com.example.lotterysystem.controller.result.*;
import com.example.lotterysystem.dao.dataobject.UserDO;
import com.example.lotterysystem.service.UserService;
import com.example.lotterysystem.service.VerificationCodeService;
import com.example.lotterysystem.service.dto.UserDTO;
import com.example.lotterysystem.service.dto.UserLoginDTO;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import com.example.lotterysystem.service.enums.UserIdentityEnum;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(
            @Validated @RequestBody UserRegisterParam param) {
        //日志打印
        logger.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        //调用Service层服务进行访问
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("/user/update")
    public CommonResult<Boolean> update(@Validated @RequestBody UpdateUserParam param) {
        logger.info("修改用户信息, param:{}", JacksonUtil.writeValueAsString(param));
        Boolean result = userService.update(param);
        return CommonResult.success(result);
    }

    /**
     * 根据id获取用户信息
     */
    @RequestMapping("/user/userInfo")
    public CommonResult<DetailUserInfoResult> userInfo(@RequestParam("userId") Long id) {
        logger.info("获取用户信息, userId:{}", id);
        UserDO userDO = userService.getUserInfo(id);
        return CommonResult.success(convertToDetailUserInfoResultList(userDO));
    }

    private DetailUserInfoResult convertToDetailUserInfoResultList(UserDO userDO) {
        DetailUserInfoResult result = new DetailUserInfoResult();
        result.setName(userDO.getUserName());
        result.setMail(userDO.getEmail());
        result.setPhoneNumber(userDO.getPhoneNumber().getValue());
        return result;
    }

    /**
     * 发送验证码服务
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        logger.info("sendVerificationCode phoneNumber:{}", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody UserPasswordLoginParam param) {
        logger.info("userPasswordLogin UserPasswordLoginParam:{}",
                JacksonUtil.writeValueAsString(param));

        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if(null == userLoginDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }

        UserLoginResult result = new UserLoginResult();
        result.setToken(userLoginDTO.getToken());
        result.setIdentity(userLoginDTO.getIdentity().name());
        return result;
    }

    /**
     * 短信验证码登录
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(@Validated @RequestBody ShortMessageLoginParam param) {
        logger.info("shortMessageLogin ShortMessageLoginParam:{}",
                JacksonUtil.writeValueAsString(param));

        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity, String name) {
        logger.info("findBaseUserInfo identity:{}", identity);
        List<UserDTO> userDTOList = userService
                .findUserInfo(UserIdentityEnum.forName(identity), name);
        return CommonResult.success(convertToUserInfoResultList(userDTOList));
    }

    @RequestMapping("/user/record-list")
    public CommonResult<List<UsersWinningRecordResult>> findUsersWinningRecord(PageParam param, Integer userId) {
        logger.info("查询用户的中奖记录, userId:{}", userId);
        List<UsersWinningRecordResult> winningRecordResultList = userService.findUsersWinningRecord(userId);
        return CommonResult.success(winningRecordResultList);
    }

    @RequestMapping("/user/delete")
    public CommonResult<Boolean> deleteUser(Long userId) {
        logger.info("删除用户, userId:" + userId);
        Boolean result = userService.deleteUser(userId);
        return CommonResult.success(result);
    }

    
    private List<BaseUserInfoResult> convertToUserInfoResultList(List<UserDTO> userDTOList) {

        if(CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }

        return userDTOList.stream()
                .map(userDTO -> {
                    BaseUserInfoResult result = new BaseUserInfoResult();
                    result.setUserId(userDTO.getUserId());
                    result.setUserName(userDTO.getUserName());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }).collect(Collectors.toList());
    }



    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        if(null == userRegisterDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
